import {
  request,
  requestPay,
  validator
} from '../../utils/requestUtils';

import { userBehavior } from '../../behaviors/userBehavior'

import {
  formatTime,
} from '../../utils/util';

Page({
  behaviors: [userBehavior],
  data: {
    checkPhonenumber: false,
    discount: 0,
    options: '',
    minHour: new Date().getHours,
    show: false, // 期望送达日期弹框
    deliveryTimeshow: false,// 期望送达时间点
    minDate: new Date().getTime(),
    currentDate: new Date().getTime(),
    form: {
      discountId: '',
      customerName: '',
      contact: '',
      payableAmount: '0',
      deliveryStr: '',//送达时间点
      remark: '',
      addrId: '',//地址id
      lines: [],//行信息
      deliveryDate: formatTime(new Date())
    },
    addr: {
      id: '',
    }
  },
  onShow() {
    // 地址设置完成后需要把缓存清空
    if (this.data.defaultAddr && this.data.defaultAddr.id) {
      console.log('缓存中获取地址', this.data.defaultAddr)
      this.setData({
        'form.addrId': this.data.defaultAddr.id
      })
      this.setDefaultAddr({})
      if (this.options.good) {
        let good = JSON.parse(decodeURIComponent(this.options.good));
        this.createOrder(good);
      } else if (this.options.id) {
        this.getOrderById(this.options.id, this.data.defaultAddr.id)
      } else {
        this.getOrder();
      }
    }

  },

  // 输入框方法
  onChange(event) {
    console.log('event.detail.value', event)
    switch (event.currentTarget.dataset['input']) {
      case 'phone':
        this.setData({
          "form.phone": event.detail,
        })
        break;
      case 'contact':
        this.setData({
          "form.contact": event.detail,
        })
        break;
    }
  },
  onLoad(options) {
    console.log('options2', JSON.parse(JSON.stringify(options)))
    this.getDefaultAddr();
    this.checkUserInfo();
  },

  // 获取用户的手机号，如果不存在则提示授权获取
  async checkUserInfo() {
    const result = await request({
      url: `/checkUserInfo`,
      method: "GET"
    })
    if (result.data.code == 200 && !result.data.data.phonenumber) {
      this.setData({
        checkPhonenumber: true
      })
    }

  },
  // 选择期望送达日期
  onShowDateTimerPopUp() {
    this.setData({
      show: true
    })
  },

  // 送达时间
  onDeliveryStrPopUp() {
    this.setData({
      deliveryTimeshow: true,
      minHour: new Date().getHours()
    })
  },
  // 期望送达日期取消按钮 以及 关闭弹框时触发
  onCancelDeliveryStrPicker() {
    this.setData({
      deliveryTimeshow: false
    })
  },

  // 期望送达日期确定按钮
  onConfirmDeliveryStrPicker(event) {
    const timeRes = event.detail
    this.setData({
      'form.deliveryStr': timeRes,
      deliveryTimeshow: false
    })
  },
  // 期望送达日期确定按钮
  onConfirmTimerPicker(event) {
    const timeRes = formatTime(new Date(event.detail))
    this.setData({
      show: false,
      'form.deliveryDate': timeRes,
    })
  },

  // 期望送达日期取消按钮 以及 关闭弹框时触发
  onCancelTimePicker() {
    this.setData({
      show: false,
      minDate: new Date().getTime(),
      currentDate: new Date().getTime()
    })
  },

  // 选择提货方式
  sekectDeliveryType() {
    console.log('测试')
    let component = this.selectComponent('#dictCon')
    if (component) {
      component.addhow('delivery_type');
    }
  },
  // 数据字典返回
  dictConfirm(e) {
    if (e.detail.key == "delivery_type") {
      this.setData({
        'form.deliveryType': e.detail.dictValue,
        'form.deliveryTypeName': e.detail.dictLabel,
      })
      // 重新设置单据信息
      if (this.options.good) {
        let good = JSON.parse(decodeURIComponent(this.options.good));
        this.createOrder(good);
      } else if (this.options.id) {
        this.getOrderById(this.options.id, this.data.form.addrId)
      } else {
        this.getOrder();
      }
    }
  },
  getAmount() {
    return 100
  },
  // 跳转到收货地址
  toAddress() {
    wx.navigateTo({
      url: '/pages/customer_addrss/index?source=pay'
    })
  },
  //获取订单信息
  async getOrder() {
    const result = await request({
      url: `/bus/customer/order/cart2Order`,
      method: "POST",
      data: this.data.form
    })
    if (result.data.code == 200) {
      this.setData({
        form: result.data.data
      })
    }
  },
  //获取订单信息
  async getOrderById(id, addrId) {
    const result = await request({
      url: `/bus/customer/order/detail`,
      method: "POST",
      data: {
        orderId: id,
        addrId: addrId,
        deliveryType: this.data.form.deliveryType

      }
    })
    if (result.data.code == 200) {
      result.data.data.deliveryDate = ''// 送达时间重新选
      this.setData({
        form: result.data.data
      })
    }
  },
  //通过商品id生成订单信息
  async createOrder(good) {
    const result = await request({
      url: `/bus/customer/order/product2Order`,
      method: "POST",
      data: { ...good, ...this.data.form }
    })
    if (result.data.code == 200) {
      this.setData({
        form: result.data.data
      })
    }
  },
  //获取默认地址
  async getDefaultAddr() {
    const result = await request({
      url: `/bus/customer/addr/defualtAddr`,
      method: "GET"
    })
    if (result.data.code == 200) {
      this.setData({
        'form.addrId': result.data.data ? result.data.data.id : '',
      })
      if (this.options.good) {
        let good = JSON.parse(decodeURIComponent(this.options.good));
        this.createOrder(good);
      } else if (this.options.id) {
        this.getOrderById(this.options.id, '')
      } else {
        this.getOrder();
      }

    }
  },
  // 提交订单
  async submitOrder() {
    console.log('this.data.form', this.data.form)
    let postMpdel = JSON.parse(JSON.stringify(this.data.form))
    const { valid } = await this.validatorAddress(postMpdel)
    console.log('校验结果')
    if (!valid) return
    const result = await request({
      url: `/bus/customer/order`,
      method: "POST",
      data: this.data.form
    })
    if (result.data.code == 200) {
      let payRes = await requestPay(result.data.data);
      console.log('payRes.errMsg', payRes.errMsg)
      if (payRes.errMsg == 'requestPayment:ok') {
        wx.showToast({
          title: '支付成功',
          icon: 'none'
        })
        setTimeout(() => {
          this.getCartNum()
        }, 1000);

        wx.navigateTo({
          url: '/pages/customer_order_list/index',
        })
      }
    }
  },
  // 数据校验
  validatorAddress(params) {
    console.log('params', params)
    const nameRegExp = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$'
    const phoneReg = '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$'
    const rules = {
      contact: [
        { required: true, message: '请输入收货人姓名' },
        { pattern: nameRegExp, message: '收货人姓名不合法' }
      ],
      phone: [
        { required: true, message: '请输入收货人手机号' },
        { pattern: phoneReg, message: '收货人手机号不合法' }
      ]
    }
    return validator(params, rules)
  },
  // 设置订单备注
  onTextAreaChange(e) {
    this.setData({
      'form.remark': e.detail.value
    })
  },
  //获取购物车数量
  async getCartNum() {
    const result = await request({
      url: `/bus/customer/cart/cartNum`,
      method: "GET"
    })
    if (result.data.code == 200) {
      this.setCarNum(result.data.data)
    }
  },
  // 优惠卷弹窗
  showDiscount() {
    let component = this.selectComponent('#discount')
    if (component) {
      component.addShow(this.data.form.payableAmount);
    }
  },
  // 选中优惠卷
  discountConfirm(e) {
    console.log('e22', e.detail)
    if(!e.detail){
      this.setData({
        discount: 0,
        'form.discountId': ''
      })
      return
    }
    this.setData({
      discount: e.detail.price,
      'form.discountId': e.detail.id
    })
  },
   getPhoneNumber(e) {
    wx.login({
      success: async res => {
        console.log('code:' + res.code);
        const result = await request({
          url: `/updateUserInfo`,
          method: "POST",
          data:{
            code:res.code,
            iv:e.detail.iv,
            encryptedData: e.detail.encryptedData
          }
        })
        if (result.data.code == 200) {
          this.setData({
            checkPhonenumber: false
          })
        }
      }
    })
  },
})
